package com.xiguaji.tiktok.v1;

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.xiguaji.boot.toolkit.JsonUtil;
import com.xiguaji.tiktok.config.exception.ParamsException;
import com.xiguaji.tiktok.v1.user.validate.UserHandler;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.HashMap;
import java.util.Map;

@RequestMapping("/v1/")
public class BaseController extends UserHandler {

    protected <T> T  getParam(String json,String key) throws ParamsException {
        Map<String,T> pam = new HashMap<>();
        pam = JsonUtil.jsonParse(pam.getClass(),json);
        T val = pam.get(key);

        if(null == val){
            throw new ParamsException();
        }
        return val;
    }

    protected <T> T  getParam(Class<T> clazz,String json,String key) throws ParamsException {
        Map pam = new HashMap<>();
        pam = getParam(pam.getClass(),json);

        if(clazz.getName().contains("String")){
            return (T)pam.get(key).toString();
        }

        T val = getParam(clazz,pam.get(key).toString());

        if(null == val){
            throw new ParamsException();
        }
        return val;
    }

    protected <T> T  getParam(Class<T> clazz,String json) throws ParamsException {
        ObjectMapper mapper = new ObjectMapper();
        try {
            //允许使用未带引号的字段名
            mapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES, true);
            //允许使用单引号
            mapper.configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES, true);
            return mapper.readValue(json,clazz);
        } catch (JsonProcessingException e) {
            throw new ParamsException();
        }
    }
}
